<template>
  <div class="product-form-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>添加商品</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="product-form"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入商品名称" />
        </el-form-item>

        <el-form-item label="商品分类" prop="categoryId">
          <el-select 
            v-model="formData.categoryId" 
            placeholder="请选择商品分类"
            @change="handleCategoryChange"
          >
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 规格选择部分 -->
        <el-form-item label="商品规格">
          <el-radio-group v-model="hasSpecs" @change="handleSpecTypeChange">
            <el-radio :label="false">无规格商品</el-radio>
            <el-radio :label="true">多规格商品</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 无规格商品表单 -->
        <template v-if="!hasSpecs">
          <el-form-item label="商品价格" prop="singlePrice">
            <el-input-number 
              v-model="formData.singlePrice"
              :precision="2"
              :step="0.1"
              :min="0"
              controls-position="right"
            />
          </el-form-item>

          <el-form-item label="商品库存" prop="singleStock">
            <el-input-number 
              v-model="formData.singleStock"
              :precision="0"
              :step="1"
              :min="0"
              controls-position="right"
            />
          </el-form-item>
        </template>

        <!-- 多规格商品设置 -->
        <template v-if="hasSpecs">
          <el-form-item label="选择规格">
            <div class="spec-actions">
              <el-button type="primary" @click="showSpecSelector">选择规格</el-button>
              <el-button type="success" @click="goToCreateSpec">创建新规格</el-button>
            </div>
            
            <!-- 已选规格展示 -->
            <div v-if="selectedSpecs.length > 0" class="selected-specs">
              <div v-for="spec in selectedSpecs" :key="spec.id" class="spec-item">
                <div class="spec-header">
                  <span>{{ spec.name }}</span>
                  <el-button type="danger" link @click="removeSpec(spec)">删除</el-button>
                </div>
                <div class="spec-values">
                  <el-tag
                    v-for="value in spec.values"
                    :key="value"
                    closable
                    @close="removeSpecValue(spec, value)"
                  >
                    {{ value }}
                  </el-tag>
                </div>
              </div>
            </div>
          </el-form-item>
        </template>

        <el-form-item label="商品主图" prop="mainImage">
          <el-upload
            class="product-image-uploader"
            :show-file-list="false"
            :http-request="uploadMainImage"
            :before-upload="beforeImageUpload"
          >
            <img v-if="formData.mainImage" :src="formData.mainImage" class="preview-image" />
            <el-icon v-else class="uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip" v-if="!formData.mainImage">支持 JPG/PNG/GIF 格式，大小不超过 2MB</div>
        </el-form-item>

        <el-form-item label="商品图片" prop="subImages">
          <el-upload
            class="product-images-uploader"
            :show-file-list="true"
            list-type="picture-card"
            :http-request="uploadSubImage"
            :on-remove="handleSubImageRemove"
            :before-upload="beforeImageUpload"
            :limit="5"
            multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">最多可上传 5 张图片，支持 JPG/PNG/GIF 格式，大小不超过 2MB</div>
        </el-form-item>

        <el-form-item label="商品详情" prop="detail">
          <el-input
            v-model="formData.detail"
            type="textarea"
            :rows="4"
            placeholder="请输入商品详情"
          />
        </el-form-item>

        <el-form-item label="是否新品" prop="isNew">
          <el-radio-group v-model="formData.isNew">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="商品状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">创建商品</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 规格选择对话框 -->
    <el-dialog
      v-model="specSelectorVisible"
      title="选择规格"
      width="800px"
    >
      <el-table
        :data="customSpecs"
        style="width: 100%"
        @selection-change="handleSpecSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="规格名称" />
        <el-table-column label="规格值">
          <template #default="{ row }">
            <el-tag
              v-for="value in row.values"
              :key="value"
              size="small"
              class="spec-value-tag"
            >
              {{ value }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="specSelectorVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSpecSelection">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getCategoryTree } from '@/api/category'
import { 
  createProduct, 
  uploadProductImage,
  getMerchantSpecTemplates
} from '@/api/product'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const formRef = ref(null)
const categories = ref([])
const userStore = useUserStore()

// 规格相关
const hasSpecs = ref(false)
const specSelectorVisible = ref(false)
const customSpecs = ref([])
const selectedSpecs = ref([])

// 表单数据
const formData = ref({
  name: '',
  categoryId: '',
  singlePrice: 0,
  singleStock: 0,
  mainImage: '',
  subImages: [],
  detail: '',
  status: 1,
  isNew: 1
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  singlePrice: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  mainImage: [
    { required: true, message: '请上传商品主图', trigger: 'change' }
  ],
  detail: [
    { required: true, message: '请输入商品详情', trigger: 'blur' }
  ]
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await getCategoryTree()
    if (res?.code === 200 && res.data) {
      categories.value = flattenCategoryTree(res.data)
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 将分类树扁平化为列表
const flattenCategoryTree = (tree) => {
  const result = []
  const flatten = (items, parentName = '') => {
    items.forEach(item => {
      const fullName = parentName ? `${parentName} / ${item.name}` : item.name
      result.push({
        id: item.id,
        name: fullName
      })
      if (item.children && item.children.length > 0) {
        flatten(item.children, fullName)
      }
    })
  }
  flatten(tree)
  return result
}

// 获取规格列表
const fetchSpecs = async () => {
  try {
    // 获取商家自定义规格
    const res = await getMerchantSpecTemplates()
    if (res?.code === 200 && res.data) {
      customSpecs.value = res.data
    }
  } catch (error) {
    console.error('获取规格列表失败:', error)
    ElMessage.error('获取规格列表失败')
  }
}

// 处理分类变化
const handleCategoryChange = (categoryId) => {
  if (categoryId) {
    fetchSpecs()
  }
}

// 显示规格选择器
const showSpecSelector = () => {
  specSelectorVisible.value = true
  fetchSpecs()
}

// 跳转到创建规格页面
const goToCreateSpec = () => {
  router.push('/merchant/product/spec')
}

// 处理规格类型变化
const handleSpecTypeChange = (val) => {
  if (!val) {
    selectedSpecs.value = []
  }
}

// 处理规格选择变化
const handleSpecSelectionChange = (selection) => {
  // 临时存储选中的规格
  const tempSelectedSpecs = selection.map(spec => ({
    name: spec.name,
    values: [...spec.values]
  }))
  
  // 更新已选规格列表
  selectedSpecs.value = tempSelectedSpecs
}

// 确认规格选择
const confirmSpecSelection = () => {
  specSelectorVisible.value = false
}

// 移除规格
const removeSpec = (spec) => {
  const index = selectedSpecs.value.findIndex(s => s.id === spec.id)
  if (index !== -1) {
    selectedSpecs.value.splice(index, 1)
  }
}

// 移除规格值
const removeSpecValue = (spec, value) => {
  const specIndex = selectedSpecs.value.findIndex(s => s.id === spec.id)
  if (specIndex !== -1) {
    const valueIndex = selectedSpecs.value[specIndex].values.indexOf(value)
    if (valueIndex !== -1) {
      selectedSpecs.value[specIndex].values.splice(valueIndex, 1)
    }
  }
}

// SKU图片上传
const uploadSkuImage = async (params, row) => {
  try {
    const res = await uploadProductImage(params.file)
    if (res.code === 200 && res.data) {
      row.image = res.data
      ElMessage.success('图片上传成功')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  }
}

// 图片上传前验证
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 修改上传方法
const uploadMainImage = async (params) => {
  try {
    const res = await uploadProductImage(params.file)
    if (res.code === 200 && res.data) {
      formData.value.mainImage = res.data
      ElMessage.success('主图上传成功')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  }
}

const uploadSubImage = async (params) => {
  try {
    const res = await uploadProductImage(params.file)
    if (res.code === 200 && res.data) {
      if (!formData.value.subImages) {
        formData.value.subImages = []
      }
      formData.value.subImages.push(res.data)
      ElMessage.success('图片上传成功')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  }
}

// 附图移除处理
const handleSubImageRemove = (file) => {
  const index = formData.value.subImages.indexOf(file.url)
  if (index !== -1) {
    formData.value.subImages.splice(index, 1)
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const submitData = {
      name: formData.value.name,
      categoryId: formData.value.categoryId,
      mainImage: formData.value.mainImage,
      subImages: formData.value.subImages,
      detail: formData.value.detail,
      status: formData.value.status,
      isNew: formData.value.isNew,
      hasSpecs: hasSpecs.value
    }

    // 根据是否有规格添加不同的数据
    if (!hasSpecs.value) {
      submitData.singlePrice = formData.value.singlePrice
      submitData.singleStock = formData.value.singleStock
    } else {
      // 将规格数据转换为字符串
      submitData.specs = JSON.stringify(selectedSpecs.value.map(spec => ({
        name: spec.name,
        values: spec.values
      })))
    }

    const res = await createProduct(submitData)
    if (res.code === 200) {
      ElMessage.success('商品创建成功')
      router.push('/merchant/product/list')
    } else {
      ElMessage.error(res.message || '创建失败')
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('请检查表单填写是否正确')
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
    formData.value.mainImage = ''
    formData.value.subImages = []
  }
}

onMounted(() => {
  fetchCategories()
})
</script>

<style scoped>
.product-form-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-form {
  max-width: 800px;
  margin: 0 auto;
}

.product-image-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.product-image-uploader:hover {
  border-color: var(--el-color-primary);
}

.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.preview-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 8px;
}

:deep(.el-upload--picture-card) {
  width: 148px;
  height: 148px;
  line-height: 148px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 148px;
  height: 148px;
}

.spec-actions {
  margin-bottom: 16px;
}

.selected-specs {
  margin-top: 16px;
}

.spec-item {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 12px;
  margin-bottom: 12px;
}

.spec-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.spec-values {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.spec-value-tag {
  margin-right: 4px;
}

.sku-image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 60px;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.sku-image-uploader:hover {
  border-color: #409EFF;
}

.sku-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>


